package com.sumainfor.pc.gmio.service.impl;

import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.DiDeferredApplyMapper;
import com.sumainfor.pc.gmio.dao.DiWithdrawalApplyMapper;
import com.sumainfor.pc.gmio.dao.UtilsMapper;
import com.sumainfor.pc.gmio.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.gmio.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.gmio.service.DiDeferredApplyService;
import com.sumainfor.pc.gmio.service.DiWithdrawalApplyService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 延期
 */
@Service
public class DiWithdrawalApplySerivceImpl implements DiWithdrawalApplyService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(DiWithdrawalApplySerivceImpl.class);
    @Autowired
    private DiWithdrawalApplyMapper diWithdrawalApplyMapper;
    @Autowired
    private UtilsMapper utilsMapper;
    @Autowired
    private ZpcMktFeign zpcMktFeign;
    @Autowired
    private ZzuulFeign zzuulFeign;
    /**
     * 退租申请
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addDiWith(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                if(params.get("PaId")==null || params.get("HouId")==null || params.get("HouInfoId")==null
                        || params.get("TenId")==null || params.get("DropoutTime")==null || params.get("Belongsbank")==null
                        || params.get("Banknumber")==null){
                    return  result.putFailed("参数不正确");
                }
                //组装消息通知参数
                Map<String,Object> messageMap=new HashMap<String,Object>();
                messageMap.put("MeType","4");//4.市场部-服务中心经理
                messageMap.put("Title","（"+params.get("HouInfoId")+"）退房，验收");//4.市场部-服务中心经理
                messageMap.put("IfJump","0");//是否可以跳转页面 0.否 1.是
                // messageMap.put("Neturl","4");//跳转URL（sys-sell/contact）
                messageMap.put("by", "auto");//操作人
                messageMap.put("term", "2");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                messageMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(messageMap);
                messageMap.put("Content",messageMap.get("instm")+"注意！有新的退房验收待处理 请及时验收！");//4.市场部-服务中心经理
                //去市场部新增消息通知
                JsonResult zuulResult=zzuulFeign.addMessage(messageMap);
                if (zuulResult.get("errorCode")!=null && !zuulResult.get("errorCode").toString().equals("0")){
                    return result.putFailed("服务器繁忙");
                }
                //内码
                String UUID="";
                int number=0;
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "WitapId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_withdrawal_apply");
                }});

                if(uuid!=null){
                    number=Integer.valueOf(uuid.get("uuid").toString());
                    UUID= ComUtils.getLocalTrmSeqNum("wi",number);
                }else{
                    UUID=ComUtils.getLocalTrmSeqNum("wi",0);
                }
                params.put("WitapId",UUID);//内码
                params.put("by", "auto");//操作人
                params.put("term", "1");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                params.put("ApplyTime", params.get("instm"));//强制退审核时间
                Integer count=diWithdrawalApplyMapper.addDiWith(params);
                if (count > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("服务器繁忙");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } catch (Exception e) {
                result.putFailed("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } finally {
            lock.unlock();
        }
        return result;
    }
    /**
     * 查询退租申请列表
     */
    @Override
    public List<Map<String,Object>> getDiWithdrawalApplyList(Map<String,Object> params){
        List<Map<String,Object>> list=diWithdrawalApplyMapper.getDiWithdrawalApplyList(params);
        List<String> houInfoIdList=new ArrayList<String>();
        for (Map<String,Object> map : list){
            if (map.get("HouInfoId")!=null){
                houInfoIdList.add(map.get("HouInfoId").toString());
            }
        }
        //到市场部查询房源信息
        params.put("houInfoIdList",houInfoIdList);
        JsonResult result=zpcMktFeign.getHouPactApplyList(params);
        System.out.println("市场部返回的参数:"+result);
        if (result.get("errorCode").equals("0")) {
            //市场部的房源列表
            List<Map<String,Object>> mktlist=(List<Map<String,Object>>)result.get("result");
            for (Map<String,Object> giomap : list){
                if (giomap.get("HouInfoId")!=null){
                    for (Map<String,Object> mktmap : mktlist) {
                        if (mktmap.get("HouInfoId")!=null) {
                            if (MapUtils.getString(giomap, "HouInfoId").equals(MapUtils.getString(mktmap, "HouInfoId"))) {
                                giomap.putAll(mktmap);
                            }
                        }
                    }
                }

            }
        }
        return list;
    }
    /*
     * 查询退租申请总数
     * */
    public Integer getDiWithdrawalApplyListCount(Map<String, Object> params){
        return diWithdrawalApplyMapper.getDiWithdrawalApplyListCount(params);
    }
    /**
     * 租客端查询是否发起过退租申请
     */
    public JsonResult getDiWithdrawalApplyCount(Map<String,Object> params){
        JsonResult result=new JsonResult();
        if (params.get("PaId")==null ){
            return result.putFailed("参数不正确");
        }
        Map<String,Object> map=diWithdrawalApplyMapper.getDiWithdrawalApplyCount(params);
        if (map!=null){
            result.put(map);
        }else{
            result.putFailed("服务器繁忙");
        }
        return result;
    }
    /**
     * 租客取消退租申请
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateDilApply(Map<String,Object> params){
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                if (params.get("WitapId")==null ){
                    return result.putFailed("参数不正确");
                }
                params.put("Status",2);//申请上架状态（0 待上架 1已上架 2已取消）
                params.put("by", "auto");//操作人
                params.put("term", "1");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                Integer count = diWithdrawalApplyMapper.updateDiCancelApply(params);
                if (count>0){
                    result.putSuccess("操作成功");
                }
                else{
                    result.putFailed("服务器繁忙");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } catch (Exception e) {
                result.putFailed("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
}
